//app.js
var commonData = require('/data/data.js');
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  showMsg: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
  },

  //检测登录状态
  wxCheckLoginStatus: function () {
    //if (wx.getStorageSync('STATUS')) return;这个缓存是永久的不好用
    var that = this;
    var res = false;
    wx.checkSession({
      success: function () {
        //session 未过期，并且在本生命周期一直有效
        if (that.globalData.userId == "") {
          //防止刷新页面，登录状态在，用户ID没了
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                res = that.wxGetUserInfo();
              }
              else {
                wx.authorize({
                  scope: 'scope.userInfo',
                  success() {
                    // 后续调用 wx.startRecord 接口不会弹窗询问
                    res = that.wxGetUserInfo();
                  },
                  fail() {
                    //用户拒绝的处理办法
                    wx.showModal({
                      title: '提示',
                      content: '您点击了拒绝授权,将无法正常使用,点击确定重新获取授权。',
                      success: function (res) {
                        if (res.confirm) {
                          wx.openSetting({
                            success: (res) => {
                              if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                                res = that.wxGetUserInfo();
                              }
                            }, fail: function (res) {

                            }
                          })

                        }
                      }
                    })
                  }
                })
              }
            }
          })
        } else {
          
        }
      },
      fail: function () {
       
        //登录态过期
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              res = that.wxGetUserInfo();
            }
            else {
              wx.authorize({
                scope: 'scope.userInfo',
                success() {
                  // 后续调用 wx.startRecord 接口不会弹窗询问
                  res = that.wxGetUserInfo();
                },
                fail() {
                  //用户拒绝的处理办法
                  wx.showModal({
                    title: '提示',
                    content: '您点击了拒绝授权,将无法正常使用,点击确定重新获取授权。',
                    success: function (res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success: (res) => {
                            if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                              res = that.wxGetUserInfo();
                            }
                          }, fail: function (res) {

                          }
                        })

                      }
                    }
                  })
                }
              })
            }
          }
        })

      }
    })
    return res;
  },
  //公共获取用户信息方法
  wxGetUserInfo: function () {
    var res = false;
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        this.globalData.userInfo = res.userInfo;
        //获取用户信息后登录存储seesion
        res = this.wxLogin(res.userInfo);
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
    return res;
  },
  wxLogin: function (userInfo) {
    var that = this;
    var res = false;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: that.appSetting.host + "Weixin/Login?code=" + res.code,
            data: {
              avatarUrl: userInfo.avatarUrl,
              city: userInfo.city,
              country: userInfo.country,
              gender: userInfo.gender,
              language: userInfo.language,
              nickName: userInfo.nickName,
              province: userInfo.province
            },
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
           
              if (res.data.Status == 0) {
                //存储登录状态
                that.globalData.userInfo = res.data.Result;
                that.getUserInfo(res.data.Result.UserId)
                res = true;
                //that.getCurrentUserPrice();
              } else {
                that.showMsg(res.data.Message);
              }

            }
          })
        } else {
          that.showMsg("获取用户登录信息失败");
          //wx.showToast("获取用户登录信息失败");
        }
      }
    });
    return res;
  },
  //加载当前用户相关信息,
  getUserInfo: function (userid) {
    var that = this;
    wx.request({
      url: that.appSetting.host + "weixin/UserPowers?userId=" + userid,
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res);
        if (res.data.Status == 0) {
          commonData.needStudyPowers = res.data.Result.NotHasPowers;
          commonData.powers = res.data.Result.HasPowers;
          commonData.currentFightPowers = res.data.Result.CurrentFightPowers;
          commonData.stopMonsterSkill = res.data.Result.StopSpeacialSkill;
          commonData.allHartSkill = res.data.Result.AllHartSpeacialSkill;
        } else {
          that.showMsg(res.data.Message);
        }

      }
    })
  },
  //异步加载怪物信息和难度配置信息
  getMonstersAndConfigs: function () {
    var that = this;
    wx.request({
      url: that.appSetting.host + "weixin/GetMonstersAndConfig",
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res);
        if (res.data.Status == 0) {
          commonData.monsters = res.data.Result.Monsters;
          commonData.refreshConfig.easyConfig = res.data.Result.EasyConfig;
          commonData.refreshConfig.hardConfig = res.data.Result.HardConfig;
          commonData.refreshConfig.hellConfig = res.data.Result.DiYuConfig;
        } else {
          that.showMsg(res.data.Message);
        }

      }
    })
  },
  //获取最新用户猫晶,并且刷新
  getCurrentUserPrice: function () {
    if (this.globalData.userInfo == null)
      this.showMsg("数据异步加载中,请稍后");
    var that = this;
    wx.request({
      url: this.appSetting.host + "weixin/GetUserCatPrice?userId=" + this.globalData.userInfo.UserId,
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res);
        var _user = that.globalData.userInfo;
        _user.CatPrice = res.data.Result;
        if (res.data.Status == 0) {
          that.globalData.userInfo = _user;
        } else {
          that.showMsg(res.data.Message);
        }

      }
    })
  },
  //分享到群成功后请求
  sharePage:function(){
    
    var that = this;
    wx.request({
      url: this.appSetting.host + "weixin/SharePage?userId=" + this.globalData.userInfo.UserId,
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.Status == 0) {
          that.getCurrentUserPrice();
        } else {
          that.showMsg(res.data.Message);
        }

      }
    })
  },
  globalData: {
    userInfo: null,
    userId: "",
    aaaaa:123
  },
  appSetting: {
   // host: 'http://192.168.39.75:8018/api/wxone/'
   //host: 'http://192.168.0.104:8085/api/wxone/'
   host: 'https://wxapi.zixunmanyou.com/api/wxone/'
  }

})